import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 水平进度条提示: 在跳转路由时使用
import 'nprogress/nprogress.css' // 水平进度条样式
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title' // 获取应用头部标题的函数

// 5.1引入获取组件方法
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
const _import = require('./router/import-' + process.env.NODE_ENV)

NProgress.configure({ showSpinner: false }) // NProgress

const whiteList = ['/login'] // 白名单

router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已经是登录成功状态,就直接进入主页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // 请求获取用户信息
          await store.dispatch('user/getInfo')

          if (store.getters.menus.length < 1) {
            global.antRouter = []
            next()
          }

          // 5.2.1过滤路由
          const menus = filterAsyncRouter(store.getters.menus)
          // 5.2.2动态添加路由
          router.addRoutes(menus)
          const lastRou = [{ path: '*', redirect: '/404', hidden: true }]
          router.addRoutes(lastRou)
          // 5.2.3将路由数据传递给全局变量，做侧边栏菜单渲染工作
          global.antRouter = menus
          next({ ...to, replace: true })
        } catch (error) {
          // 当上述方法发生异常时,移除原获取的token,重新执行登录
          await store.dispatch('user/resetToken')
          Message.error({
            message: error || 'Has Error'
          })
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

// 5.2.4
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        try {
          // 导入组件
          route.component = _import(route.component)
        } catch (error) {
          // 导入组件
          route.component = _import('home/index')
        }
      }
    }
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route.children
    }
    return true
  })
  return accessedRouters
}
